package com.ee.chat.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ee.chat.admin.service.IHostService;
import com.ee.chat.admin.service.IOperationService;
import com.ee.chat.common.bean.Result;
import com.ee.chat.common.dao.*;
import com.ee.chat.common.entity.*;
import com.ndhutu.ee.util.DateUtil;
import com.ndhutu.ee.util.StringUtil;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Service
public class HostServiceImpl implements IHostService {
    @Resource
    HostMapper hostMapper;
    @Resource
    UserMapper userMapper;
    @Resource
    IOperationService operationService;
    @Resource
    HostTitleMapper hostTitleMapper;
    @Resource
    HostPhotosMapper hostPhotosMapper;
    @Resource
    UserDynamicMapper userDynamicMapper;
    @Resource(name = "stringRedisTemplate")
    StringRedisTemplate redisTemplate;
    @Resource
    HostCallContentMapper hostCallContentMapper;
    @Resource
    UserRemarkLogMapper remarkLogMapper;

    @Override
    public Result list(HttpServletRequest request, Integer page, Integer limit, Integer online,
                       Integer title, String keyword, String time) throws Exception {
        Map<String, Object> data = new HashMap<>();

        if(title == null && online == null && StringUtil.isEmpty(keyword) && StringUtil.isEmpty(time)){
            HttpSession session = request.getSession(true);
            List<String> userPermissions = (List<String>)session.getAttribute("userPermissions");
            if(!userPermissions.contains("/host/viewList")){
                data.put("hosts", new ArrayList<>());
                data.put("total", 0);

                return Result.returnSuccess(data);
            }
        }

        Date beginTime = null, endTime = null;
        if(!StringUtil.isEmpty(time)){
            String[] arr = time.split(" - ");
            beginTime = DateUtil.parse(arr[0]);
            endTime = DateUtil.parse(arr[1]);
        }
        Page<Map<String, Object>> p = new Page<>(page, limit);
        IPage<Map<String, Object>> iPage = hostMapper.list(p, online, title, keyword, beginTime, endTime);

        data.put("hosts", iPage.getRecords());
        data.put("total", iPage.getTotal());

        operationService.addOperationLog(request, "获取主播列表数据");

        return Result.returnSuccess(data);
    }

    @Override
    public Result updateLevel(HttpServletRequest request, Integer id, Integer level, Integer wi) throws Exception {
        Host host = hostMapper.selectById(id);
        host.setLevel(level);
        host.setWi(wi);
        hostMapper.updateById(host);

        operationService.addOperationLog(request, host.getUserId() + "变更等级为：" + level + "，变更权重为：" + wi);

        return Result.returnSuccess(null);
    }

    @Override
    public Result updateTitle(HttpServletRequest request, Integer userId, Integer title) throws Exception {
        HostTitle hostTitle = hostTitleMapper.selectByUserId(userId);

        if(title == null){
            if(hostTitle != null){
                hostTitleMapper.deleteById(hostTitle.getId());

                operationService.addOperationLog(request, userId + "删除主播头衔");
            }
        }else{
            if(hostTitle == null){
                hostTitle = new HostTitle(userId, title);
                hostTitleMapper.insert(hostTitle);

                operationService.addOperationLog(request, userId + "添加主播头衔");
            }else{
                hostTitle.setTitle(title);

                hostTitleMapper.updateById(hostTitle);

                operationService.addOperationLog(request, userId + "更新主播头衔");
            }
        }

        return Result.returnSuccess(null);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result cancelAudit(HttpServletRequest request, Integer userId) throws Exception {
        //删除主播身份
        QueryWrapper<Host> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        hostMapper.delete(wrapper);

        //删除照片墙
        hostPhotosMapper.deleteByUserId(userId);

        //删除头衔
        QueryWrapper<HostTitle> wrapper2 = new QueryWrapper<>();
        wrapper2.eq("user_id", userId);
        hostTitleMapper.delete(wrapper2);

        //收费动态改为免费
        QueryWrapper<UserDynamic> wrapper3 = new QueryWrapper<>();
        wrapper3.eq("user_id", userId);
        wrapper3.eq("`status`", 0);
        UserDynamic userDynamic = new UserDynamic();
        userDynamic.setConfigId(0);
        userDynamicMapper.update(userDynamic, wrapper3);

        //删除招呼
        QueryWrapper<HostCallContent> wrapper4 = new QueryWrapper<>();
        wrapper4.eq("user_id", userId);
        hostCallContentMapper.delete(wrapper4);

        //删除redis推荐库
        String key1 = "host:hot:online:";
        for(int i=3; i>=0 ; i--){
            redisTemplate.opsForZSet().remove(key1+i, userId+"");
        }

        //强制用户退出app
        User user = userMapper.selectById(userId);
        String key = "token:"+user.getToken();
        redisTemplate.expire(key, -1, TimeUnit.MINUTES);

        operationService.addOperationLog(request, userId+"被取消认证");

        return Result.returnSuccess(null);
    }
}
